package com.thoughtworks.collection;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.List;
import java.util.stream.Collectors;

public class Reduce {

    List<Integer> arrayList;

    public Reduce(List<Integer> arrayList) {
        this.arrayList = arrayList;
    }

    public int getMaximum() {
        // 获取数组中的最大值
       return arrayList.stream().max(Integer::compareTo).get();
    }

    public double getMinimum() {
        //获取数组中的最小值
        return arrayList.stream().min(Integer::compareTo).get();
    }

    public double getAverage() {
        // 获取数组的平均值
        double sum = arrayList.stream().reduce(0, (pre, cur) -> pre + cur);
        return sum/arrayList.size();
    }

    public double getOrderedMedian() {
        // 获取数组中位数
        double result;
        List<Integer> arr = arrayList.stream().sorted().collect(Collectors.toList());
        int len = arr.size();
        int left = arr.get(len / 2 - 1);
        int right = arr.get(len / 2);
        result = len % 2 == 0 ? (double) (left + right) / 2 : arr.get((len - 1) / 2);
        return result;
    }

    public int getFirstEven() {
        //获取数组中第一个偶数
        return arrayList.stream().filter(num -> num % 2 == 0).findFirst().get();
    }

    public int getIndexOfFirstEven() {
        //获取数组中第一个偶数的下标
        int firstEven=arrayList.stream().filter(num -> num % 2 == 0).findFirst().get();
        return arrayList.indexOf(firstEven);
    }

    public boolean isEqual(List<Integer> arrayList) {
        return arrayList.containsAll(this.arrayList) && this.arrayList.containsAll(arrayList);
    }

    public Double getMedianInLinkList(SingleLink singleLink) {
        for (int num : arrayList) {
            singleLink.addTailPointer(num);
        }
        int index = arrayList.size() / 2;
        if (arrayList.size() % 2 == 0) {
            int left = (int) singleLink.getNode(index);
            int right = (int) singleLink.getNode(index + 1);
            return (left + right) / 2.0;
        } else {
            return (Double) singleLink.getNode(index + 1);
        }

    }

    public int getLastOdd() {
        //获取数组中最后一个奇数的下标
        List<Integer> oddList = arrayList.stream().filter(num -> num % 2 != 0)
                .collect(Collectors.toList());
        return oddList.get(oddList.size() - 1);
    }

    public int getIndexOfLastOdd() {
        //获取数组中最后一个奇数
        int num = getLastOdd();
        return arrayList.indexOf(num);
    }
}
